import React, { Suspense, lazy,ReactNode } from "react"
import { Navigate } from "react-router-dom"

const NotFound = lazy(() => import("@/pages/notFound"))
const Login = lazy(() => import("@/pages/login/index"))
const Register = lazy(() => import("@/pages/register/index"))
const data = JSON.parse(sessionStorage.getItem("routers"))

const allAsyncRoutes = data ? data : []
const Auth = (props) => {
  const token = sessionStorage.getItem("token") || false
  return token ? <>{props.children}</> : <Navigate to="/login" />
}

// 解决路由跳转闪屏问题
const lazyComponent = (element: ReactNode): ReactNode => {
  return <Suspense fallback={<>Loading</>}>
    {element}
  </Suspense>
}

const anyRoute = [
  {
    path: "/*",
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <NotFound />
      </Suspense>
    )
  }
]

//递归操作
function createRoute(route, token) {
  // console.log(route);
  const { path, element, children, requireAuth, name, status } = route

  let renderedElement = (
    <Suspense fallback={<div>Loading...</div>}>
      {React.createElement(lazy(() => import(/* @vite-ignore */ element)))}
    </Suspense>
  )

  renderedElement = <Auth>{renderedElement}</Auth>

  const renderedChildren = children && children.map((childRoute) => createRoute(childRoute, token))

  return {
    path,
    element: renderedElement,
    children: renderedChildren,
    name,
    requireAuth,
    status
  }
}

function createRoutes(routes) {
  return routes.map((route) => createRoute(route, true))
}

const dynamicRoutes = createRoutes(allAsyncRoutes)

const staticRouter = [
  {
    path: "/",
    element: <Navigate to="/login" />
  },
  {
    path: "/login",
    element: (
      // <Suspense>
      //   <Login />
      // </Suspense>
      lazyComponent(<Login />)
    )
  },
  {
    path: "/register",
    element: (
      // <Suspense fallback={<div>Loading...</div>}>
      //   <Register />
      // </Suspense>
      lazyComponent(<Register />)
    )
  },
  {
    path: "/*",
    element: (
      // <Suspense fallback={<div>Loading...</div>}>
      //   <NotFound />
      // </Suspense>
      lazyComponent(<NotFound />)
    )
  }
]

export { staticRouter, dynamicRoutes, anyRoute }
